# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2022/6/5 14:57
# @Author : xyjiang1216
# @Email : jiangxuyan@nudt.edu.cn
# @File : fwd_tbl_structure.py
# @Version: planner_builder 1.0

import ctypes
from tsn_builder_struct.table_length import *

c_uint32 = ctypes.c_uint32


# 转发表表项的详细字段组成
class IndexEntry_bits(ctypes.BigEndianStructure):
    _fields_ = [
        # entry1
        ('valid', c_uint32, 1),
        ('reserved', c_uint32, 25),
        ('etc_index', c_uint32, 6)
    ]


# 组织成32bit数据的转发表表项
class IndexEntry_bytes(ctypes.BigEndianStructure):
    _fields_ = [
        ('entry1', c_uint32, 32)
    ]


# 转发表表项联合体
class IndexEntry_union(ctypes.Union):
    _fields_ = [
        ("bit", IndexEntry_bits),
        ("byte", IndexEntry_bytes)
    ]


# 转发表表项
class IndexEntry:
    def __init__(self,
                 flow_id: int,
                 flow_type: int,
                 index_entry: IndexEntry_union):
        self.flow_id = flow_id
        self.flow_type = flow_type
        self.index_entry = index_entry


# 一个节点上的转发表
class IndexTblEachNode:
    def __init__(self,
                 node_id: int) -> None:
        self.node_id = node_id
        self.tbl_len = INDEX_TBL_LEN
        self.entry_cnt = 0
        # 转发表的默认表项为空
        self.tbl_each_node = [IndexEntry(None, None, None)
                              for i in range(self.tbl_len)]

    def append_entry(self,
                     entry: IndexEntry) -> None:
        if self.entry_cnt < self.tbl_len:
            self.tbl_each_node[self.entry_cnt] = entry
            self.entry_cnt += 1
        else:
            print('The number of index entries exceeds '
                  'the hardware limit, please check the index_xml')
            print('node_id: %d' % self.node_id)
            exit(0)


class IndexTbl:
    def __init__(self):
        self.tbl_set = []

    def append_tbl(self,
                   tbl: IndexTblEachNode) -> None:
        self.tbl_set.append(tbl)
